﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Physis.Core.Sponsor {

    public class Sponsor  : Core.Entity.Entity {

        #region Private Properties

        private Int64 entityId = 0;

        private Int64 sponsorTypeId = 0;

        private String nationalEmployerId = String.Empty;


        private SponsorType sponsorType = null;

        #endregion


        #region Public Properties

        public override Entity.Enumerations.EntityType EntityType { get { return Entity.Enumerations.EntityType.Sponsor; } }

        public override Boolean Person { get { return false; } set { base.Person = false; } }

        public override Boolean CanBePerson { get { return false; } }

        public Int64 EntityId { get { return entityId; } }


        public Int64 SponsorTypeId {

            get { return sponsorTypeId; }

            set {

                if (sponsorTypeId != value) {

                    sponsorTypeId = value;

                    sponsorType = null;  // LAZY LOAD 

                }

            }

        }

        public SponsorType SponsorType {

            get {

                if (sponsorType == null) { sponsorType = Application.Core.Sponsor.SponsorType (sponsorTypeId, true); }

                return sponsorType;

            }

        }

        public String SponsorTypeName { get { return ((SponsorType != null) ? SponsorType.Name : String.Empty); } }


        public String NationalEmployerId { get { return nationalEmployerId; } set { nationalEmployerId = Data.Functions.SetValueMaxLength (value, Data.DataTypeConstants.BusinessId); } }

        #endregion


        #region Constructors

        public Sponsor (Application forApplication) : base (forApplication) {

            return;

        }

        public Sponsor (Application forApplication, Int64 forId) : base (forApplication, forId) {

            return;

        }

        #endregion


        #region Database Functions

        protected override String SelectStatementById(Int64 forId = 0) {

            String selectStatement = String.Empty;

            selectStatement += "SELECT * \r\n"; 

            selectStatement += "  FROM Sponsor JOIN Entity ON Sponsor.EntityId = Entity.Id \r\n";

            selectStatement += "  WHERE Sponsor.Id = " + forId; 

 	        return selectStatement;

        }

        protected override Dictionary<String, String> Validate () {

            Dictionary<String, String> validationErrors = base.Validate ();


            return validationErrors;

        }

        public override void MapDataFields (System.Data.DataRow currentRow) {

            base.MapDataFields (currentRow);


            entityId = Data.Readers.DataReader.Int64FromDatabase (currentRow, "EntityId");

            SponsorTypeId = Data.Readers.DataReader.Int32FromDatabase (currentRow, "SponsorTypeId");

            NationalEmployerId = Data.Readers.DataReader.StringFromDatabase (currentRow, "NationalPlanId");


            return;

        }

        public override Boolean Save () {

            Boolean success = false;

            Boolean useTransaction = (Application.EnvironmentDatabase.OpenTransactions == 0);



            try {

                Dictionary<String, String> validationErrors = Validate ();

                if (validationErrors.Count > 0) {

                    Application.SetLastException (new Exception ("Invalid [" + validationErrors.Keys.First () + "]: " + validationErrors.Values.First ()));

                    return false;

                }

                UpdateModifiedToSessionUser ();


                if (useTransaction) { Application.EnvironmentDatabase.BeginTransaction (); }


                // TRY TO SAVE THE ENTITY FIRST 

                success = base.Save (EntityId);

                if (success) {

                    // DETERMINE IF THIS IS A NEW INSURER/ENTITY COMBINATION AND MOVE THE ID 

                    // IDENTITY VALUE GENERATED IN BASE CLASS FROM ID TO ENTITY ID 

                    if (entityId == 0) {

                        entityId = Id;

                        Id = 0; 

                    }

                }

                else { throw Application.LastException; }


                System.Data.IDbCommand command = Application.EnvironmentDatabase.CreateCommand (ObjectType + "_InsertUpdate");

                command.CommandType = System.Data.CommandType.StoredProcedure;


                Application.EnvironmentDatabase.AppendCommandParameter (command, "Id", Id);


                Application.EnvironmentDatabase.AppendCommandParameter (command, "EntityId", EntityId);

                Application.EnvironmentDatabase.AppendCommandParameter (command, "SponsorTypeId", SponsorTypeId);

                Application.EnvironmentDatabase.AppendCommandParameter (command, "NationalEmployerId", NationalEmployerId, 20);


                Application.EnvironmentDatabase.AppendCommandParameter (command, "ModifiedId", Application.Session.UserAccountName, 60);

                success = (command.ExecuteNonQuery () > 0);

                if (success) { SetIdentity (); }


                if (useTransaction) { Application.EnvironmentDatabase.CommitTransaction (); }

            }

            catch (Exception exception) {

                if (useTransaction) { Application.EnvironmentDatabase.RollbackTransaction (); }

                success = false;

                Application.SetLastException (exception);

            }

            return success;

        }

        #endregion


        #region Public Methods 

        public Boolean Enroll (DateTime effectiveDate, Int64 enrollmentActionReasonId, Int64 parentSponsorId, Int64 programId) {

            Boolean success = false;


            SponsorEnrollment sponsorEnrollment = new SponsorEnrollment (Application, Id, effectiveDate, enrollmentActionReasonId, parentSponsorId, programId);

            success = sponsorEnrollment.Save ();


            return success;

        }

        #endregion 

    }

}
